package com.example.springsecurity.service.impl;

import com.example.springsecurity.domain.LoginUser;
import com.example.springsecurity.domain.ResponseResult;
import com.example.springsecurity.domain.SysUser;
import com.example.springsecurity.service.LoginService;
import com.example.springsecurity.uilts.JwtUtil;
import com.example.springsecurity.uilts.RedisCache;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Objects;

@Service
public class LoginServiceImpl implements LoginService {

    @Resource
    private AuthenticationManager authenticationManager;
    @Resource
    private RedisCache redisCache;

    @Override
    public String Login(SysUser user) {

        UsernamePasswordAuthenticationToken authRequest
                = new UsernamePasswordAuthenticationToken(user.getUserName(),user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authRequest);

        if(Objects.isNull(authenticate)){
            throw new RuntimeException("用户名或密码错误");
        }

        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();

        // 登录成功 ，创建一个token（身份卡）,jwt
        String token = JwtUtil.createJWT(loginUser.getSysUser().getId().toString());

        // 把登录的用户存到缓存里
        // key的规范，login:id
        redisCache.setCacheObject("login:" + loginUser.getSysUser().getId(), loginUser);
        return token;
    }

    @Override
    public void LoginOut() {
        // 拿到当前用户
        LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        // 从缓存中删除用户
        redisCache.deleteObject("login:"+loginUser.getSysUser().getId());
    }
}
